<template>
  <contentModel v-if="modelValue" title="编辑" @open="open" @close="cancel">
    <template #footer>
      <a-space>
        <a-button type="outline" @click="handleCancel(record, rowIndex)"
          >取消</a-button
        >
        <a-button
          type="primary"
          :loading="loading"
          @click="handleSubmit(record, rowIndex)"
          >保存</a-button
        >
      </a-space>
    </template>
    <table-container
      v-model:columns="columns"
      v-model:is-fullscreen="isFullscreen"
      :loading="boxTableLoading"
      :all-columns="allColumns"
      @refresh="getBoxTableList"
    >
      <template #container-side>
        <a-space>
          <a-button type="primary" @click="addRow">新增</a-button>
        </a-space>
      </template>
      <standard-table
        ref="detailTable"
        v-model:selectedKeys="detailSelectedKeys"
        :component-config="tableComponentConfig"
        :render-config="tableRenderConfig"
        :render-keys="tableRenderKeys"
        :loading="detailTableLoading"
        :data="detailTableData"
        :total="detailTableTotal"
        @init-columns-end="initColumns"
        @page-change="detailPageChange"
        @page-size-change="detailPageSizeChange"
      >
        <template #operate="{ record, rowIndex }">
          <a-button type="text" @click="handleEdit(record, rowIndex)"
            >编辑</a-button
          >
          <a-button type="text" @click="handleDelete(record, rowIndex)"
            >删除</a-button
          >
        </template>
      </standard-table>
    </table-container>
  </contentModel>
  <FaultInformationModal
    v-if="addModalVisible"
    v-model="addModalVisible"
    :select-id="selectRowId"
    :select-row="selectRow"
    @submit="addModalSubmit"
  />
</template>

<script lang="ts" setup>
  import { defineAsyncComponent, inject, ref, toRefs } from 'vue';
  import lodash from 'lodash';
  import StandardTable from '@/common/components/standard-table/index.vue';
  import TableContainer from '@/common/components/table-container/index.vue';
  import {
    getScsProductReverseList,
    updateScsProductDetail,
  } from '@/api/reverse-procurement/product-handling';
  import { Message } from '@arco-design/web-vue';
  import FaultInformationModal from './fault-information-modal.vue';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '../module-common/table-comp/base-table-config';

  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    // eslint-disable-next-line vue/require-prop-types
    selectId: {},
  });
  const emits = defineEmits(['update:modelValue']);
  const cancel = () => {
    emits('update:modelValue', false);
  };
  // const { cancel } = useModelFun();
  const selectedRow = inject('selectedRow');
  const { selectId } = toRefs(props);
  const selectRow = ref(null);
  const selectRowIndex = ref(null);
  const loading = ref(false);
  const addModalVisible = ref(false);
  const deleteProductReverseLVOList = ref([]);
  const handleSubmit = async () => {
    if (!detailTableData.value.length) {
      Message.warning({
        content: '请添加情况跟踪！',
        duration: 5 * 1000,
      });
      return;
    }
    try {
      loading.value = true;
      const form = {
        productReverseLVOList: detailTableData.value.map((item) => {
          item.scsProductReverseId = selectId?.value;
          if (item.id.includes('id-')) {
            delete item.id;
          }
          return item;
        }),
        deleteProductReverseLVOList: deleteProductReverseLVOList.value,
        id: selectId?.value,
        secretLevel: selectedRow?.value.secretLevel,
      };
      await updateScsProductDetail(form);
      Message.success({
        content: '保存成功！',
        duration: 5 * 1000,
      });
      loading.value = false;
      cancel();
    } catch (error) {
      console.log(error);
      loading.value = false;
    }
  };
  const addRow = () => {
    selectRow.value = {};
    addModalVisible.value = true;
  };
  const addModalSubmit = (row) => {
    if (row.id) {
      detailTableData.value[selectRowIndex.value] = Object.assign(
        detailTableData.value[selectRowIndex.value],
        row
      );
    } else {
      detailTableData.value.push({
        ...row,
        id: `id-${new Date()}`,
      });
    }
    addModalVisible.value = false;
  };
  const handleEdit = (row, index) => {
    selectRow.value = row;
    selectRowIndex.value = index;
    addModalVisible.value = true;
  };
  const handleDelete = (row, rowIndex) => {
    if (row.id && !row.id.includes('id-')) {
      deleteProductReverseLVOList.value.push(row);
    }
    detailTableData.value.splice(rowIndex, 1);
  };
  const handleCancel = () => {
    cancel();
  };
  // const getDetailInfo = async () => {
  //   const { data } = await getPmsReceiveDetailInfoById(selectId?.value);
  //   Object.keys(data).forEach((key) => {
  //     form[key] = data[key];
  //   });
  // };
  const columns = ref<object[]>([]);
  const allColumns = ref<object[]>([]);
  const initColumns = (data: any[]) => {
    columns.value = lodash.cloneDeep(data);
    allColumns.value = lodash.cloneDeep(data);
  };
  const init = () => {
    if (selectId?.value) {
      // getDetailTableList();
    }
  };
  // table-list
  const detailTable = ref(null);
  // const detailRenderKeys = ['orderNo', 'mdsItemCode'];
  const detailSelectedKeys = ref([]);
  const detailTableLoading = ref(false);
  const detailTableData = ref([]);
  const detailTableTotal = ref(0);
  // 当前表格要渲染哪些值
  const tableRenderKeys = [
    'situationTracking',
    'expectedReturnTime',
    'vendorEditUserName',
    'vendorEditDate',
    'operate',
  ];
  // const searchHandle = (query = {}) => {
  //   getDetailTableList(query);
  // };
  // const resetHandle = () => {
  //   getDetailTableList({});
  // };
  const open = () => {
    if (detailTableLoading.value) return;
    detailTableLoading.value = true;
    getDetailTableList();
  };
  const detailPageChange = () => {
    getDetailTableList();
  };
  const detailPageSizeChange = () => {
    getDetailTableList();
  };
  const getDetailTableList = async () => {
    // const page = detailTable.value.getStatus();
    try {
      detailTableLoading.value = true;
      const { data } = await getScsProductReverseList(selectId?.value);
      detailTableData.value = data || [];
      detailTableTotal.value = data.length;
    } finally {
      detailTableLoading.value = false;
    }
  };
  init();
</script>
